package main.java.com.rmisorter;

import main.java.com.rmisorter.sorters.ISorter;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.Observable;

@SuppressWarnings("rawtypes")
public class SorterThread extends Observable implements Runnable {
	private final String HOSTNAME = "rmisorter";
	private Thread threadSorter;
	private Comparable[] listToSort, sortedList;
	private ISortFactory fact;
	private int threadNumber = 0;
	private String sorter;
	
	public SorterThread(Comparable[] list, int iThread, String sorter, ListJoiner listJoiner) throws Exception {
		this.listToSort = list;
		this.threadNumber = iThread;
		this.sorter = sorter;
		addObserver(listJoiner);
	}
	
	private void lookupRMISorter() {
		try {
			this.fact = (ISortFactory) Naming.lookup(HOSTNAME);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

    public void start() {
    	this.threadSorter = new Thread(this);
    	this.threadSorter.start();
   }
    
    public int getThreadNumber() {
    	return threadNumber;
    }
    
	public void run() {
		long currentTime;
		
		lookupRMISorter();
		
		try {
			ISorter sorter = fact.createSorter(this.sorter);
			currentTime = System.currentTimeMillis();
			this.sortedList = sorter.sort(listToSort);
			System.out.println("r:" + (System.currentTimeMillis() - currentTime));

			setChanged();
			notifyObservers(this.sortedList);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	       



	}

}
